/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import config.Debug;
import config.Helper;
import config.Settings;
import controller.UpdateChecker;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class Content {

	private int id;
	private ContentType type;
	private String content;
	private boolean hasUpdate;
	private int server;
	private String path;

	public Content(String content, ContentType type) {
		this.content = content;
		this.type = type;
	}

	/**
	 * @param id
	 *            content_id from database table `content`
	 */
	public Content(int id) {
		this.createContentFromDatabaseById(id);
	}

	/**
	 * @param id
	 *            the container id of a container
	 * @return boolean if the container with the given container id exists,
	 *         returns true, false otherwise
	 */
	public static boolean contentExists(int id) {
		String sql = String.format("SELECT * FROM `content` WHERE `content_id`='%1$s';", id);
		Connection conn = Settings.getLocalDatabaseConnection();
		ResultSet result = null;
		Statement stmt = null;
		try {
			int numResults = Helper.getNumberOfResults(sql);
			if (numResults == 0) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			// TODO handle exception
			return false;
		} finally {
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException ex) {
				Logger.getLogger(Content.class.getName()).log(Level.SEVERE, null, ex);
			}
		}
	}

	private void createContentFromDatabaseById(int id) {
		String sql = String.format("SELECT * FROM `content` WHERE `content_id`='%1$s' LIMIT 1;", id);
		Connection conn = Settings.getLocalDatabaseConnection();
		ResultSet result = null;
		Statement stmt = null;
		try {
			int numResults = Helper.getNumberOfResults(sql);
			if (numResults <= 0) {
				// throw new
				// com.mysql.jdbc.exceptions.MySQLDataException("There is no content with id: "
				// + id);
				Debug.log("There is no content with id: " + id, Debug.WARNING_LEVEL);
				content = "invalid content";
				path = "invalid content";
				type = ContentType.IMAGE;
				return;
			}
			stmt = conn.createStatement();
			result = stmt.executeQuery(sql);
			result.first();
			this.id = id;
			this.type = ContentType.getContentType(result.getString("content_type"));
			this.path = result.getString("content");
			this.hasUpdate = result.getBoolean("has_update");
			this.server = result.getInt("server");
			String[] pieces = path.split("/");
			if (pieces.length > 0) {
				this.content = pieces[pieces.length - 1];
			} else {
				this.content = path;
			}
		} catch (SQLException ex) {
			Logger.getLogger(Playlist.class.getName()).log(Level.SEVERE, null, ex);
			result = null;
		} finally {
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException ex) {
				Logger.getLogger(Content.class.getName()).log(Level.SEVERE, null, ex);
			}

		}
	}

	public boolean hasUpdate() {

		String sql = "SELECT * FROM content WHERE content_id = '" + this.getId() + "';";
		Connection conn = Settings.getLocalDatabaseConnection();
		ResultSet result = null;
		Statement stmt = null;
		try {
			int numResults = Helper.getNumberOfResults(sql);
			if (numResults <= 0) {
				return hasUpdate;
			}
			stmt = conn.createStatement();
			result = stmt.executeQuery(sql);
			result.first();
			this.hasUpdate = result.getBoolean("has_update");
			result.close();
			result = null;
		} catch (SQLException ex) {
			Logger.getLogger(Content.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException ex) {
				Logger.getLogger(Content.class.getName()).log(Level.SEVERE, null, ex);
			}

		}

		return hasUpdate;
	}

	public boolean hasValidContent() {
		if(this.getType()==ContentType.VIDEO) {
			if(new File(new File(Settings.getResourceDirectory()+File.separator+this.getDirectory()), this.content).exists()) {
				return true;
			} else {
				System.out.println(new File(new File(this.getDirectory()), this.content).toString());
				return false;
			}
		}
		return true;
	}
	public void setHasUpdate(boolean hasUpdate) {
		this.hasUpdate = hasUpdate;
		int has_update = 0;
		if (hasUpdate) {
			has_update = 1;
			UpdateChecker.setNeedDownloadContent(true);
			File f = new File(this.getDirectory() + this.getContent());
			f.delete();
		}
		String sql = "UPDATE content SET has_update = '" + has_update + "' WHERE content_id = '" + this.getId() + "';";
		try {
			Helper.localMysqlExecute(sql);
		} catch (SQLException ex) {
			Logger.getLogger(Content.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public String getContent() {
		return content;
	}

	public int getId() {
		return id;
	}

	public ContentType getType() {
		return type;
	}

	@Override
	public String toString() {
		return this.getContent();
		// return "[" + this.getId() + "] " + "(" +
		// this.getType().toString().toLowerCase() + ") " + this.getContent();
	}

	public String getDirectory() {
		if (this.getType() == ContentType.IMAGE || this.getType() == ContentType.GIF) {
			return "images";
		} else if (this.getType() == ContentType.VIDEO) {
			return "videos";
		} else if (this.getType() == ContentType.HTML) {
			return "html";
		}
		return "";
	}

	public int getServer() {
		return server;
	}

	public static void main(String[] args) {
	}

	public String getPath() {
		return path;
	}

}
